package club.babyf.nativeai.demo.algorithm;

/**
 * _29_ReverseBetween.
 *
 * @author zhanglei.
 * @date 2025/8/8 21:13.
 * @description 反转指定范围内的链表.
 */
public class _29_ReverseBetween {

    public static class ListNode {

        int val;

        ListNode next;

        public ListNode(int val) {
            this.val = val;
        }

        public ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }

        @Override
        public String toString() {
            StringBuilder sb = new StringBuilder();
            ListNode current = this;
            while (current != null) {
                sb.append(current.val);
                ListNode next = current.next;
                if (next != null) {
                    sb.append(" -> ");
                }
                current = next;
            }
            return sb.toString();
        }

    }

    public ListNode reverseBetween(ListNode head, int left, int right) {
        if (head == null || left >= right) {
            return head;
        }

        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode pre = dummy;

        for (int i = 0; i < left - 1; i++) {
            if (pre.next == null) {
                return dummy.next;
            }
            pre = pre.next;
        }

        ListNode cur = pre.next;
        if (cur == null) {
            return dummy.next;
        }
        ListNode next;

        for (int i = 0; i < right - left; i++) {
            next = cur.next;
            cur.next = next.next;
            next.next = pre.next;
            pre.next = next;
        }

        return dummy.next;
    }

    public static void main(String[] args) {
        _29_ReverseBetween reverseBetween = new _29_ReverseBetween();

        ListNode head = new ListNode(1, new ListNode(2, new ListNode(3, new ListNode(4, new ListNode(5)))));
        System.out.println(head);

        ListNode listNode = reverseBetween.reverseBetween(head, 2, 4);
        System.out.println(listNode);
    }

}
